<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <title>用户管理</title>
        <link href="/css/modal.css" rel="stylesheet" />
    </head>
    <body>
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-title">
                    用户信息列表
                </div>
                <div class="panel-body table-responsive">
                    <table id="myTable" class="table display"></table>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">编辑用户信息</h4>
                    </div>
                    <div class="modal-body">
                        <!-- Start Row -->
                        <div class="row">

                            <div class="form-horizontal">
                                <div :class="clazz.usernameClazz">
                                    <label for="username" class="col-sm-2 control-label form-label">用户名</label>
                                    <div class="col-sm-9">
                                        <input @change="initClazz($event)" type="text" class="form-control" id="username" placeholder="admin" v-model="username" />
                                    </div>
                                </div>
                                <div :class="clazz.fullnameClazz">
                                    <label for="fullname" class="col-sm-2 control-label form-label">姓名</label>
                                    <div class="col-sm-9">
                                        <input @change="initClazz($event)" type="text" class="form-control" id="fullname" placeholder="大白" v-model="fullname"/>
                                    </div>
                                </div>
                                <div  :class="clazz.userphoneClazz">
                                    <label for="userphone" class="col-sm-2 control-label form-label">手机号</label>
                                    <div class="col-sm-9">
                                        <input @change="initClazz($event)" type="number" class="form-control" id="userphone" placeholder="1888888888" v-model="userphone"/>
                                    </div>
                                </div>
                                <div  :class="clazz.usersphoneClazz">
                                    <label for="usersphone" class="col-sm-2 control-label form-label">手机短号</label>
                                    <div class="col-sm-9">
                                        <input @change="initClazz($event)" type="number" class="form-control" id="usersphone" placeholder="68888" v-model="usersphone"/>
                                    </div>
                                </div>
                                <div  :class="clazz.emailClazz">
                                    <label for="email" class="col-sm-2 control-label form-label">电子邮箱</label>
                                    <div class="col-sm-9">
                                        <input @change="initClazz($event)" type="email" class="form-control" id="email" placeholder="email@XX.com" v-model="email"/>
                                    </div>
                                </div>
                                <div :class="clazz.userphotoClazz">
                                    <label for="userphoto" class="col-sm-2 control-label form-label">头像</label>
                                    <div class="col-sm-9">
                                        <input @change="getUserphoto($event)" type="file" accept="image/x-png,image/jpeg"
                                               class="form-control dropify" data-height="100"
                                               data-max-file-size="1M" data-max-file-size-preview="1M"
                                               id="userphoto" v-model="uphoto" />
                                        <span id="helpBlock" class="help-block">*图片仅支持.jpg / .png格式，大小1M以内*</span>
                                    </div>
                                </div>
                                <div class="form-group" v-if="roles">
                                    <label for="role" class="col-sm-2 control-label form-label">角色</label>
                                    <div class="col-sm-9">
                                        <select v-model="role" class="selectpicker form-control" id="role">
                                            <option v-for="role in roles" :value="role">{{role.roleName}}</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="status" class="col-sm-2 control-label form-label">状态</label>
                                    <div class="col-sm-9">
                                        <select v-model="status" class="selectpicker form-control" id="status">
                                            <option value="1">正常</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                        </div>
                        <!-- End Row -->
                    </div>
                    <div class="modal-footer" style="margin-top: 0px">
                        <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                        <button id="saveUserBtn" @click="saveUser()" type="button" class="btn btn-default">保存</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- End Moda Code -->

        <script>
            $(function() {
                var defOrder = [10, 'desc']; //默认排序列
                var _table = $('#myTable').DataTable({
                    dom: '<"top"Blf<"clear">>rt<"bottom"ip<"clear">>',
                    // dom: 'Bfrtip',
                    lengthMenu: [10, 25, 50, 75, 100],
                    pageLength: 10,
                    language: dtlanguage,//中文
                    select: true,
                    ordering: true,
                    order: [defOrder],//表示初期第n列降序排序，使用thymeleaf一定要把双中括号分开写
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: '/service/sysUser/queryPage',
                        type: 'post',
                        contentType: "application/json;charset=UTF-8",
                        dataType: 'json',
                        // 传给服务器的数据，可以添加我们自己的查询参数
                        data: function (param) {
                            var orderBy = '';
                            if (param.order != null && param.order.length > 0) {
                                param.order.forEach((o, i) => {
                                    orderBy += param.columns[o.column].data + " " + o.dir + ",";
                                });
                                orderBy = orderBy.substring(0, orderBy.length - 1);
                            }
                            var data = {
                                draw: param.draw,
                                search: param.search.value,
                                limit: param.length,
                                offset: param.start,
                                orderBy: orderBy
                            }
                            //当请求需要传递JSON数据格式的参数时，前台应该在JS中使用JSON.stringify()方法，将JSON数据转换成String类型
                            return JSON.stringify(data);
                        },
                        //预先处理服务器端返回的数据，修改成DT能用格式 draw、recordsTotal、recordsFiltered、data。
                        dataFilter: function (text, type) {
                            if (!isEmpty(text)) {
                                var json = JSON.parse(text);//字符串转json
                                if (json.success) {
                                    var qbean = json.data;
                                    var data = {
                                        draw: json.code,
                                        recordsTotal: qbean.total,
                                        recordsFiltered: qbean.total,
                                        data: qbean.list
                                    }
                                    text = JSON.stringify(data);//json转字符串
                                }
                            }
                            return text;//返回字符串
                        },
                        //用于处理服务器端返回的数据。 dataSrc是DataTable特有的
                        dataSrc: function (data) {
                            if (data.data == null) {
                                return '';
                            } else {
                                return data.data;
                            }
                        }
                    },
                    buttons:[
                        {
                            text:'<i class="fa fa-plus"></i>添加用户',
                            className:'btn btn-square btn-success',
                            action: function (e, dt, node, config) {
                                myFormApp.initData();//清空表单
                                $('#myModal').modal('show');
                            }
                        },{
                            text:'<i class="fa fa-lock"></i>重置密码',
                            className:'btn btn-square btn-warning',
                            action: function (e, dt, node, config) {
                                var datas = dt.rows('.selected').data();
                                if(datas!=null && datas.length>0) {
                                    swal({
                                            title: "你确定要批量重置用户密码吗?",
                                            text: "重置密码后，初始密码为用户的手机号！",
                                            type: "warning",
                                            showCancelButton: true,
                                            confirmButtonText: "确定",
                                            cancelButtonText: "取消"
                                        },
                                        function(isConfirm){
                                            if (isConfirm) {
                                                var userIds = [];
                                                datas.each((d, i) => {
                                                    userIds.push(d.userId);
                                                });
                                                put('/service/sysUser/resetPasswords', function (result) {
                                                    if(result.success){
                                                        spop({
                                                            template: '批量重置用户密码成功',
                                                            autoclose: 5000,
                                                            style:'success'
                                                        });
                                                    }else {
                                                        spop(result.message, 'error');
                                                    }
                                                }, userIds);
                                            }
                                        });
                                }else{
                                    spop({
                                        template: '请选择要执行重置密码的行',
                                        autoclose: 5000,
                                        style:'warning'
                                    })
                                }
                            }
                        },{
                            text:'<i class="fa fa-trash-o"></i>删除用户',
                            className:'btn btn-square btn-danger',
                            action: function (e, dt, node, config) {
                                var datas = dt.rows('.selected').data();
                                if(datas!=null && datas.length>0) {
                                    swal({
                                            title: "你确定要批量删除用户吗?",
                                            text: "用户删除后，将无法登录使用系统！",
                                            type: "warning",
                                            showCancelButton: true,
                                            confirmButtonText: "确定",
                                            cancelButtonText: "取消"
                                        },
                                        function(isConfirm){
                                            if (isConfirm) {
                                                var userIds = [];
                                                datas.each((d, i) => {
                                                    userIds.push(d.userId);
                                                });
                                                put('/service/sysUser/removeList', function (result) {
                                                    if(result.success){
                                                        spop({
                                                            template: '批量删除用户成功',
                                                            autoclose: 5000,
                                                            style:'success'
                                                        });
                                                        _table.ajax.reload(null, false);//刷新列表
                                                    }else {
                                                        spop(result.message, 'error');
                                                    }
                                                }, userIds);
                                            }
                                        });
                                }else{
                                    spop({
                                        template: '请选择要执行删除的行',
                                        autoclose: 5000,
                                        style:'warning'
                                    })
                                }
                            }
                        }
                    ],
                    rowId: 'userId',
                    columns: [
                        {
                            data: 'username',
                            title: '用户名',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }, {
                            data: 'fullname',
                            title: '姓名',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }, {
                            data: 'userphone',
                            title: '手机号',
                            defaultContent: '--',
                            orderable: true
                        }, {
                            data: 'usersphone',
                            title: '短号',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }, {
                            data: 'email',
                            title: '邮箱',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }, {
                            data: 'userphoto',
                            title: '头像',
                            defaultContent: '--',
                            orderable: false,
                            render: function (data, type, row, meta) {
                                if(data==null){
                                    return '--';
                                }
                                var html = '<a data-fancybox="images" href="'+data+'" data-width="700" data-caption="'+row.username+'">\n' +
                                                '<img src="'+data+'" width="50px" alt="'+row.username+'" />\n' +
                                            '</a>\n' ;
                                return html;
                            }
                        }, {
                            data: 'roleName',
                            title: '角色',
                            defaultContent: '--',
                            orderable: true
                        }, {
                            data: 'status',
                            title: '状态',
                            defaultContent: '--',
                            orderable: true,
                            render: function (data, type, row, meta) {
                                switch (data) {
                                    case 1:
                                        return '正常';
                                }
                            }
                        }, {
                            data: 'lastLoginTime',
                            title: '最后登录时间',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }, {
                            data: 'modifyTime',
                            title: '修改时间',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }, {
                            data: 'createTime',
                            title: '创建时间',
                            defaultContent: '--',
                            orderable: true,
                            render: shotContent
                        }
                    ],
                    columnDefs: [
                        {
                            targets: 11,//最后一列 从0开始
                            title: '操作',
                            orderable: false,
                            render: function (data, type, row, meta) {
                                return [
                                    '<button type="button" class="edit-btn btn btn-info btn-icon" data-userid="' + row.userId + '"><i class="fa fa-edit"></i></button>&nbsp;&nbsp;',
                                    '<button type="button" class="psw-btn btn btn-warning btn-icon" data-userid="' + row.userId + '"><i class="fa fa-lock"></i></button>&nbsp;&nbsp;',
                                    '<button type="button" class="del-btn btn btn-danger btn-icon" data-userid="' + row.userId + '"><i class="fa fa-trash-o"></i></button>'
                                ].join('');
                            }
                        }
                    ]
                });

                //方法
                var methods = {
                    //获取所有角色
                    getRoles:function () {
                        get('/service/sysRole/getAll',function (result) {
                            if(result.success && result.data){
                                Vue.set(myFormApp, 'roles', result.data);
                                Vue.set(myFormApp, 'role', result.data[0]);
                            }else{
                                spop(result.message, 'error');
                            }
                        });
                    },
                    //保存用户信息
                    saveUser:function () {
                        if(isEmpty(this.username)){
                            spop("用户名不能为空", 'error');
                            this.$set(this.clazz,'usernameClazz','form-group has-error');
                            return;
                        }
                        if(this.username.length>32){
                            spop("用户名过长", 'error');
                            this.$set(this.clazz,'usernameClazz','form-group has-error');
                            return;
                        }
                        if(isEmpty(this.userphone)){
                            spop("手机号不能为空", 'error');
                            this.$set(this.clazz,'userphoneClazz','form-group has-error');
                            return;
                        }
                        if(this.userphone.length!==11){
                            spop("手机号格式不正确", 'error');
                            this.$set(this.clazz,'userphoneClazz','form-group has-error');
                            return;
                        }
                        if(!isEmpty(this.usersphone) && this.usersphone.length>5){
                            spop("手机短号过长", 'error');
                            this.$set(this.clazz,'usersphoneClazz','form-group has-error');
                            return;
                        }
                        if(!isEmpty(this.email)){
                            if(!isEmail(this.email)){
                                spop("邮箱地址格式不正确", 'error');
                                this.$set(this.clazz,'emailClazz','form-group has-error');
                                return;
                            }else if(this.email.length>128){
                                spop("邮箱地址过长", 'error');
                                this.$set(this.clazz,'emailClazz','form-group has-error');
                                return;
                            }
                        }

                        var _this = this;
                        put('/service/sysUser/editOne',function (result) {
                            if(result.success) {
                                spop({
                                    template: '保存成功',
                                    autoclose: 5000,
                                    style:'success'
                                });
                                if (_this.userphoto != null) {//上传头像
                                    var formData = new FormData();
                                    formData.append('userphoto', _this.userphoto);
                                    formData.append('userId', result.data.userId);
                                    fetchRequest('POST', '/service/sysUser/uploadPhoto', function (res) {
                                        if (res.success) {
                                            spop({
                                                template: '上传头像成功',
                                                autoclose: 5000,
                                                style:'success'
                                            });
                                            _table.ajax.reload(null, false);//刷新列表
                                            $('#myModal').modal('hide');
                                        } else {
                                            spop(res.message, 'error');
                                        }
                                    }, formData);
                                }else {//不需要上传头像，
                                    _this.initData();//清空表单
                                    _table.ajax.reload(null, false);//刷新列表
                                    $('#myModal').modal('hide');
                                }
                            }else {
                                spop(result.message, 'error');
                            }
                        },{
                            userId: _this.userId,
                            username: _this.username,
                            fullname: _this.fullname,
                            userphone: _this.userphone,
                            usersphone: _this.usersphone,
                            email: _this.email,
                            roleId: _this.role.roleId,
                            roleName: _this.role.roleName,
                            status: _this.status
                        });
                    },
                    //初始化输入框样式 change时调用
                    initClazz:function (event) {
                        var id = event.target.id;
                        if(this.clazz[id+'Clazz']!=='form-group'){
                            this.$set(this.clazz, id+'Clazz', 'form-group');
                        }
                        var userId = this.userId;
                        var val = event.target.value;
                        if(id==='username'){
                            get('/service/sysUser/checkUsername',function (result) {
                                if(!result.success){
                                    Vue.set(myFormApp.clazz,'usernameClazz','form-group has-error');
                                    spop(result.message, 'error');
                                }
                            },{
                                userId: userId,
                                username:val
                            });
                        }else if(id==='userphone'){
                            get('/service/sysUser/checkPhone',function (result) {
                                if(!result.success){
                                    Vue.set(myFormApp.clazz,'userphoneClazz','form-group has-error');
                                    spop(result.message, 'error');
                                }
                            },{
                                userId: userId,
                                userphone:val
                            });
                        }else if(id==='email'){
                            get('/service/sysUser/checkEmail',function (result) {
                                if(!result.success){
                                    Vue.set(myFormApp.clazz,'emailClazz','form-group has-error');
                                    spop(result.message, 'error');
                                }
                            },{
                                userId: userId,
                                email:val
                            });
                        }
                    },
                    //图片输入框change调用，判断图片大小
                    getUserphoto:function (event) {
                        this.$set(this.clazz, 'userphotoClazz', 'form-group');
                        var files = event.target.files;
                        if (files != null && files.length > 0) {
                            var size = files[0].size/1024;
                            if(size>1024){//图片大于1M
                                this.$set(this.clazz, 'userphotoClazz', 'form-group has-error');
                                spop('图片不能大于1M', 'error');
                            }else {
                                this.$set(this, 'userphoto', files[0]);
                            }
                        }else{
                            this.$set(this, 'userphoto', null);
                        }
                    },
                    //初始化表单
                    initData:function () {
                        this.$set(this,'clazz',{
                            usernameClazz:'form-group',
                            fullnameClazz:'form-group',
                            userphoneClazz:'form-group',
                            usersphoneClazz:'form-group',
                            emailClazz:'form-group',
                            userphotoClazz:'form-group'
                        });
                        this.$set(this,'userId',null);
                        this.$set(this,'username',null);
                        this.$set(this,'fullname',null);
                        this.$set(this,'userphone',null);
                        this.$set(this,'usersphone',null);
                        this.$set(this,'userphoto',null);
                        this.$set(this,'uphoto',null);
                        this.userphotodropify.clearElement();
                        this.$set(this,'email',null);
                        this.$set(this,'role', this.roles[this.roles.length-1]);
                        this.$set(this,'status',1);
                    }
                }
                //表单vue
                var myFormApp = new Vue({
                    el:'#myModal',
                    //属性
                    data:{
                        clazz:{usernameClazz:'form-group',
                            fullnameClazz:'form-group',
                            userphoneClazz:'form-group',
                            usersphoneClazz:'form-group',
                            emailClazz:'form-group',
                            userphotoClazz:'form-group'},
                        userId:null,
                        username:null,
                        fullname:null,
                        userphone:null,
                        usersphone:null,
                        userphoto:null,
                        uphoto:null,
                        userphotodropify:null,
                        email:null,
                        roles:[],
                        role:null,
                        status:1
                    },
                    methods: methods,
                    mounted:function () {
                        this.getRoles();
                        //input file 插件 初始化
                        this.userphotodropify = new Dropify(document.getElementById('userphoto'),{messages:zhlanguage});
                        // $('#userphoto').dropify({messages:zhlanguage});
                    },
                    updated: function () {}
                });


                //编辑
                $('#myTable tbody').on('click', 'button.edit-btn', function () {
                    myFormApp.initData();//清空表单
                    var userId = $(this).data('userid');
                    get('/service/sysUser/getOne',function (result) {
                        if(result.success && result.data){
                            var user = result.data;
                            Vue.set(myFormApp,'userId',userId);
                            Vue.set(myFormApp,'username',user.username);
                            Vue.set(myFormApp,'fullname',user.fullname);
                            Vue.set(myFormApp,'userphone',user.userphone);
                            Vue.set(myFormApp,'usersphone',user.usersphone);
                            Vue.set(myFormApp,'userphoto',null);
                            Vue.set(myFormApp,'uphoto',null);
                            myFormApp.userphotodropify.clearElement();
                            if(!isEmpty(user.userphoto)) {
                                myFormApp.userphotodropify.settings.defaultFile = user.userphoto;
                                myFormApp.userphotodropify.setFilename(user.userphoto);
                                myFormApp.userphotodropify.setPreview(user.userphoto);
                            }
                            Vue.set(myFormApp, 'email', user.email);
                            myFormApp.roles.forEach((item, i) => {
                                if(user.roleId===item.roleId){
                                    Vue.set(myFormApp,'role', item);
                                    return false;
                                }
                            });
                            Vue.set(myFormApp,'status',user.status);
                        }else {
                            spop(result.message,'error')
                        }
                    },{
                        userId: userId
                    });

                    $('#myModal').modal('show');
                });
                //重置密码
                $('#myTable tbody').on('click', 'button.psw-btn', function () {
                    var userId = $(this).data('userid');
                    swal({
                            title: "你确定要重置密码吗?",
                            text: "重置密码后，初始密码为用户的手机号！",
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonText: "确定",
                            cancelButtonText: "取消"
                        },
                        function(isConfirm){
                            if (isConfirm) {
                                post('/service/sysUser/resetPassword',function (result) {
                                    if(result.success){
                                        spop({
                                            template: '密码重置成功',
                                            autoclose: 5000,
                                            style:'success'
                                        });
                                    }else {
                                        spop(result.message, 'error');
                                    }
                                },{
                                    userId:userId
                                })
                            }
                        });
                });
                //删除
                $('#myTable tbody').on('click', 'button.del-btn', function () {
                    var userId = $(this).data('userid');
                    swal({
                            title: "你确定要删除用户吗?",
                            text: "用户删除后，将无法登录使用系统！",
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonText: "确定",
                            cancelButtonText: "取消"
                        },
                        function(isConfirm){
                            if (isConfirm) {
                                del('/service/sysUser/removeOne/'+userId,function (result) {
                                    if(result.success){
                                        spop({
                                            template: '用户删除成功',
                                            autoclose: 5000,
                                            style:'success'
                                        });
                                        _table.ajax.reload(null, false);//刷新列表
                                    }else {
                                        spop(result.message, 'error');
                                    }
                                })
                            }
                        });
                });

            });
        </script>
    </body>
</html>